package com.wyp.didishige.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bmob.BmobProFile;
import com.wyp.didishige.R;
import com.wyp.didishige.adapter.GridAdapter;
import com.wyp.didishige.config.Config;
import com.wyp.didishige.model.Dynamic;
import com.wyp.didishige.model.User;
import com.wyp.didishige.model.photo.PhotoInfo;
import com.wyp.didishige.utils.IntentUtil;
import com.wyp.didishige.utils.StringUtils;
import com.wyp.didishige.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.im.bean.BmobMsg;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.datatype.BmobGeoPoint;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

/**
 * 发布动态
 */
public class NewDynamicActivity extends BaseActivity implements View.OnClickListener {

    private static final int POI_SEARCH = 0;
    EditText dynamic_text;
    LinearLayout add_image;
    GridView gridview_image;
    ArrayList<PhotoInfo> hasList;
    GridAdapter girdAdapter;
    int count = 0;
    ImageView button;
    User loginUser;
    //地点
    TextView dynamic_address = null;
    TextView mTopTips = null;
    RelativeLayout layout_address = null;
    //第一次发表
    boolean isFister = false;
    //注册引导发表
    boolean isRegister = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_dynamic);

        init();
    }

    @Override
    protected void initParamter() {
        super.initParamter();
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            isFister = bundle.getBoolean(Config.KEY_NEW_FIRSTER_DYNAMIC);
            isRegister = bundle.getBoolean(Config.KEY_AFFTER_REGISTER_FIRSTER_DYNAMIC);
        }
        loginUser = userManager.getCurrentUser(User.class);
        hasList = new ArrayList<PhotoInfo>();


        girdAdapter = new GridAdapter(this, true);

        if (isRegister){
            sendMsgToNear();
        }
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("发布动态");
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        gridview_image = (GridView) findViewById(R.id.gridview_image);
        dynamic_address = (TextView) findViewById(R.id.dynamic_address);
        mTopTips = (TextView) findViewById(R.id.mTopTips);
        layout_address = (RelativeLayout) findViewById(R.id.layout_address);
        dynamic_text = (EditText) findViewById(R.id.dynamic_text);

        add_image = (LinearLayout) findViewById(R.id.add_image);

        button = new ImageView(this);
    }

    @Override
    protected void initWidgetListener() {
        super.initWidgetListener();
        girdAdapter.setRemoveListener(new GridAdapter.RemoveListener() {
            @Override
            public void remove(int position) {
                girdAdapter.remove(position);
                if (hasList.size() == 0) {
                    gridview_image.setVisibility(View.GONE);
                }
            }
        });
        add_image.setOnClickListener(this);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                publish();

            }
        });

        layout_address.setOnClickListener(this);

    }

    @Override
    protected void initWidgetState() {
        super.initWidgetState();
        girdAdapter.setmList(hasList);
        gridview_image.setAdapter(girdAdapter);

        if (isFister) {
            mTopTips.setText(R.string.dy_top_text_first);
        } else if (isRegister) {
            mTopTips.setText(R.string.dy_top_text_new_register);
        } else {
            mTopTips.setText(R.string.dy_top_text_normal);
        }
    }

    private void publish() {
        String[] files = new String[hasList.size()];
        for (int i = 0; i < hasList.size(); i++) {
            files[i] = hasList.get(i).getPath_absolute();
        }
        if (files == null || files.length == 0) {
            ToastUtil.showShort(this, "最少需要一张图片哟~");
            return;
        }

        loading.setTitle("提示");
        loading.setMessage("努力发布中ING");
        loading.setIndeterminate(false);
        loading.show();

        BmobProFile.getInstance(this).uploadBatch(files, new com.bmob.btp.callback.UploadBatchListener() {
            @Override
            public void onSuccess(boolean isFinish, String[] fileNames, String[] urls, BmobFile[] files) {
                if (isFinish) {
                    saveDynamiC(files);
                }

            }

            @Override
            public void onProgress(int curIndex, int curPercent, int total, int totalPercent) {
            }

            @Override
            public void onError(int statuscode, String errormsg) {
                loading.cancel();
                ShowToast("发布失败，请重试," + errormsg);
            }
        });

    }

    private void saveDynamiC(BmobFile[] files) {
        Dynamic dynamic = new Dynamic();
        if (files != null) {
            dynamic.setImages(files);
        }
        dynamic.setAuthor(loginUser);
        if (!StringUtils.isNullOrEmpty(dynamic_address.getText().toString())) {
            dynamic.setAddress(dynamic_address.getText().toString());
        }
        dynamic.setAuthorId(loginUser.getObjectId());
        dynamic.setContent(dynamic_text.getText().toString());
        dynamic.setLocation(loginUser.getLocation());
        dynamic.save(NewDynamicActivity.this, new SaveListener() {
            @Override
            public void onSuccess() {
                if (isRegister || isFister) {
                    IntentUtil.start_activity(NewDynamicActivity.this, MainActivity.class);
                } else {
                    setResult(RESULT_OK);
                }
                finish();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                loading.cancel();
            }

            @Override
            public void onFailure(int i, String s) {
                ShowToast("发布失败，请重试");
            }
        });
    }
    /**
     * 给附近的人发送消息
     */
    private void sendMsgToNear() {
        getLocation();
    }

    // 定位相关
    LocationClient mLocClient;
    BmobGeoPoint geoPoint;
    public MyLocationListenner myListener = new MyLocationListenner();

    /**
     * 定位
     */
    private void getLocation() {
        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location != null) {
                geoPoint = new BmobGeoPoint(location.getLongitude(), location.getLatitude());
            } else {
                // 无定位数据默认北京中心
                double cLat = 39.909230;
                double cLon = 116.397428;
                geoPoint = new BmobGeoPoint(cLon, cLat);
            }

            getNearByList();
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    private void getNearByList() {
        if (geoPoint == null) {
            getLocation();
            return;
        }

        BmobQuery<User> query = new BmobQuery<User>();

        query.addWhereWithinKilometers("location", geoPoint, 30);
        query.addWhereNotEqualTo("objectId", loginUser.getObjectId());
        query.setLimit(20);
        query.findObjects(this, new FindListener<User>() {
            @Override
            public void onSuccess(List<User> users) {
                if (users != null) {
                    BmobMsg msg = null;
                    for (User user : users) {
                        msg = BmobMsg.createTextSendMsg(NewDynamicActivity.this, user.getObjectId(), "我是新注册的窝友，我在" + loginUser.getCommunity() + "，一起来聊天吧");
                        manager.sendTextMessage(user, msg);
                    }
                }
            }

            @Override
            public void onFinish() {
            }

            @Override
            public void onError(int i, String s) {
                ShowToast(s);
            }
        });
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case POI_SEARCH:
                    if (data != null && data.getExtras() != null) {
                        String address = data.getExtras().getString(PoiSearchActivity.ADDRESS);
                        dynamic_address.setText(address);
                    }

                    break;
                case 1:
                    ArrayList<PhotoInfo> list = (ArrayList<PhotoInfo>) data.getSerializableExtra("hasList");
                    if (list != null) {
                        hasList.addAll(list);
                        count = hasList.size();
                        if (hasList != null && hasList.size() != 0) {
                            gridview_image.setVisibility(View.VISIBLE);
//                            girdAdapter.appendToList(list);
                            girdAdapter.notifyDataSetChanged();
                        }
                    }

                    break;
                default:
                    break;

            }
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();

        inflater.inflate(R.menu.menu_new_dynamic, menu);

        MenuItem item = menu.findItem(R.id.action_publish);
        button.setBackgroundResource(R.drawable.blue_bg_selector);
        button.setImageResource(R.drawable.ic_topbar_confirm_white);
        button.setPadding(40, 20, 40, 20);
        item.setActionView(button);
        actionBar.setCustomView(button,
                new ActionBar.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.MATCH_PARENT, Gravity.RIGHT));

        return true;
    }

    @Override
    public void onBackPressed() {
        exit();
    }

    private void exit(){
        if (!StringUtils.isNullOrEmpty(dynamic_text.getText().toString())) {
            alertDialog();
        } else {
            if (isRegister || isFister) {
                IntentUtil.start_activity(NewDynamicActivity.this, MainActivity.class);
            } else {
                setResult(RESULT_OK);
            }
            finish();
        }
    }
    private void alertDialog() {
        builder.setTitle("提示");
        builder.setMessage("退出此次编辑?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.show();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == android.R.id.home) {
            exit();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_image:
                if (count >= 8) {
                    Toast.makeText(NewDynamicActivity.this, "最多选择8张图片！", Toast.LENGTH_SHORT).show();
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putInt("count", count);
                    IntentUtil.start_activity_for_result(NewDynamicActivity.this, SelectPhotoActivity.class, 1, bundle);
                }
                break;
            case R.id.layout_address:
                Bundle bundle = new Bundle();
                bundle.putString(PoiSearchActivity.ADDRESS, loginUser.getStreet());
                IntentUtil.start_activity_for_result(this, PoiSearchActivity.class, POI_SEARCH, bundle);
                break;
        }
    }


}
